// 创建班级
import express from 'express';
import pool from "../importantApi/db_connection.js";

const router = express.Router();
router.post("/", async (req, res) => {
    const {className, userId} = req.body;
    if (!className || !userId) {
        return res.status(401).json({
            code: 401,
            msg: "缺少必要参数"
        })
    }
    let date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    let createTime = `${year}-${String(month).padStart(2,'0')}-${String(day).padStart(2,'0')} ${String(hour).padStart(2,'0')}:${String(minute).padStart(2,'0')}`
    try {
        let [result] = await pool.query(`
            insert into classinfo (class_name, user_id, createtime)
            values ('${className}', '${userId}', '${createTime}')
        `)
        if (result.affectedRows === 0) {
            return res.status(201).json({
                code: 201,
                msg: "班级创建失败"
            })
        }
        // 将创建好的班级和用户加入班级记录
        await pool.query(`
            insert into user_class (class_id, user_id, jointime)
            values (${result.insertId}, ${userId}, '${createTime}')
        `)
        return res.status(200).json({
            code: 200,
            msg: "班级创建成功",
            data:{
                class_id: result.insertId
            }
        })
    } catch (err) {
        console.log(err)
        return res.status(500).json({
            code: 500,
            msg: "班级创建错误：server error"
        })
    }
})
export default router;